from entity import Admin
import json
from util import mapping, jformat
from models import db
from sqlalchemy import and_

def userInfo():
    return json.dumps({
        "avatar": "http://www.icosky.com/icon/png/System/Scrap/Administrator%202.png",
        "name": "admin",
        "roles": ["admin"],
        "data": ["index", "order-manage", "order-list", "product-manage", "product-list", "review-manage",
                 "return-goods","admin-manage","old-chart","camera",
                 "goods", "goods-list", "goods-classify", "permission", "user-manage", "role-manage", "menu-manage"]
    })


def getAll():
    admins = Admin.query.all()
    print(admins)
    adminList = []
    for admin in admins:
        adminList.append(mapping.adminToDict(admin))
    print(adminList)
    return json.dumps(adminList)


def get_id_name():
    admins = Admin.query.with_entities(Admin.ID, Admin.name)
    print(admins)
    adminList = []
    for admin in admins:
        adminList.append(mapping.to_id_name(admin, 'admin'))
    print(adminList)
    return adminList


def getById(id):
    # 通过id搜索数据库
    one = Admin.query.get(id)
    admin = mapping.adminToDict(one)
    return json.dumps(admin)


def getById_withoutMapping(id):
    # 通过id搜索数据库
    one = Admin.query.get(id)
    # admin = mapping.adminToDict(one)
    return one


def update(request_data):
    # 是否存在
    if db.session.query(Admin).filter(Admin.ID == request_data['ID']).count() != 0:
        db.session.query(Admin).filter(Admin.ID == request_data['ID']).update(request_data)
        db.session.commit()
        return 'ok'
    else:
        return 'error'


def add(request_data):
    print(request_data)
    db.session.execute(
        Admin.__table__.insert(),
        request_data
    )
    db.session.commit()
    return 'ok'


def deleteByID(ID):
    Admin.query.filter(Admin.ID == ID).delete()
    # 提交会话
    db.session.commit()
    return 'del'


def initAdmin(data):
    admin = Admin()
    for item in dir(admin):
        if item.startswith('_'):
            continue
        print(item)
        if item in data.keys():
            admin.__setattr__(item, data[item])
            print(data[item])
    return admin


def login(req):
    if db.session.query(Admin).filter(and_(Admin.name == req['name'], Admin.password == req['password'])).count()!=0:
        return '0'
    else:
        return '1'
